package com.online.customerchatserver.controller;

import com.online.customerchatserver.entity.Message;
import com.online.customerchatserver.service.*;
import com.online.customerchatserver.util.MessageTypeEnums;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

/**
 * 顾客聊天信息服务控制器
 *
 * @author hsc
 * @create 2018-04-24 11:10
 */
@RestController
public class CustomerChatServerController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    RedisService redisService;

    @Autowired
    FindAgentService findAgentService;

    @Autowired
    WebSocketService webSocketService;

    @Autowired
    MessageService messageService;

    @Autowired
    ApiImageUploadService apiImageUploadService;

    /**
     * 文本消息处理服务
     *
     * @return
     */
    @PostMapping(value = "/textMessageServer")
    public Map textMessageServer(@RequestBody Map map) {
        Map<String, Object> maps = new HashMap<String, Object>(2);
        // 企业ID
        int eId = (int) map.get("e_id");
        // 消息ID
        Long msgId = (Long) map.get("msg_id");
        // 创建时间
        Long createTime = ((Integer) map.get("create_time")) + 0L;
        // 消息内容
        String content = (String) map.get("content");


        // 查找坐席和会话服务
        map.remove("content");
        map.remove("create_time");
        map.remove("msg_id");

        Map agentMaps = findAgentService.findAgentServer(map);
        // 客服ID -1 : 坐席在忙
        int serviceId = (int) agentMaps.get("service_id");

        String openId = (String) agentMaps.get("open_id");

        // 会话ID
        Integer sessionId = (Integer) agentMaps.get("session_id");

        // 将消息放到消息缓存列表中
        Message message = new Message();
        String uuid = String.valueOf(msgId);
        message.setUuid(uuid);
        message.setContent(content);
        message.setType(MessageTypeEnums.TEXT.getValue());
        message.setDirection(0);
        message.setCompanyId(String.valueOf(eId));
        message.setSessionId(String.valueOf(sessionId));
        message.setReadStatus(0);
        message.setCreateTime(new Timestamp(createTime));
        redisService.add(sessionId + "", message);

        // java消息异步接口批处理
        if ("".equals(uuid) || message == null) {
            this.logger.info("saveCustomerMessage：参数为空");
            maps.put("type", 1);
            return maps;
        }
        messageService.saveCustomerMessage(uuid, message);

        // 通知调度有未读信息
        Map messageMap = new HashMap(3);
        messageMap.put("service_id", serviceId);
        messageMap.put("session_id", sessionId);
        messageMap.put("e_id", eId);
        messageMap.put("open_id", openId);
        Map sendMessageMaps = webSocketService.sendMessages(messageMap);
        // 0：成功 1：坐席不在线
        int sendMessageResult = (int) sendMessageMaps.get("result");
        if (sendMessageResult == 1) {
            maps.put("type", 1);
            return maps;
        }

        if (-1 == serviceId) {
            maps.put("type", 1);
            return maps;
        }

        maps.put("type", 0);
        return maps;
    }

    /**
     * 图片消息处理服务
     *
     * @return
     */
    @PostMapping(value = "/imgMessageServer")
    public Map imgMessageServer(@RequestBody Map map) {

        Map<String, Object> maps = new HashMap<String, Object>(2);
        String openId = (String) map.get("open_id");
        // 企业ID
        int eId = (int) map.get("e_id");
        // 消息ID
        Long msgId = (Long) map.get("msg_id");
        // 创建时间
        Long createTime = ((Integer) map.get("create_time")) + 0L;
        // 媒体ID
        String mediaId = (String) map.get("media_id");
        // 返回结果
        int type = 0;

        // 查找坐席和会话服务
        map.remove("url");
        map.remove("create_time");
        map.remove("msg_id");
        Map agentMaps = findAgentService.findAgentServer(map);
        // 客服ID -1 : 坐席在忙
        Integer serviceId = (Integer) agentMaps.get("service_id");
        // 坐席在忙
        if ("-1".equals(serviceId)) {
            type = 1;
        }

        // 会话ID
        Integer sessionId = (Integer) agentMaps.get("session_id");

        // 构建消息对象
        Message message = new Message();
        String uuid = String.valueOf(msgId);
        message.setUuid(uuid);
        message.setContent(mediaId);
        message.setType(MessageTypeEnums.IMG.getValue());
        message.setDirection(0);
        message.setCompanyId(String.valueOf(eId));
        message.setSessionId(String.valueOf(sessionId));
        message.setReadStatus(0);
        message.setCreateTime(new Timestamp(createTime));

        // 发送给java消息异步接口批处理
        if ("".equals(uuid) || message == null) {
            this.logger.info("saveCustomerMessage：参数为空");
            maps.put("type", 1);
            return maps;
        }
        Map<String, String> param = new HashMap<>();
        param.put("mediaId",mediaId);
        Map result = this.apiImageUploadService.uploadFromWeChat(param);
        if ((Integer) result.get("result") == 0) {
            message.setContent(result.get("url").toString());
            messageService.saveCustomerMessage(uuid, message);
        } else {
            this.logger.info("图片未上传成功");
            maps.put("type", 1);
            return maps;
        }

        // 将消息放到消息缓存列表中
        String url = (String) map.get("pic_url");
        message.setContent(url);
        redisService.add(sessionId + "", message);

        // 通知调度有未读信息
        Map messageMap = new HashMap(3);
        messageMap.put("service_id", serviceId);
        messageMap.put("session_id", sessionId);
        messageMap.put("e_id", eId);
        messageMap.put("open_id", openId);
        Map sendMessageMaps = webSocketService.sendMessages(messageMap);
        // 0：成功 1：坐席不在线
        int sendMessageResult = (int) sendMessageMaps.get("result");
        if (sendMessageResult == 1) {
            type = 1;
        }

        maps.put("type", type);
        return maps;

    }

    /**
     * 语音消息处理服务
     *
     * @return
     */
    @PostMapping(value = "/voiceMessageServer")
    public Map voiceMessageServer(@RequestBody Map map) {

        Map<String, Object> maps = new HashMap<String, Object>(2);
        String openId = (String) map.get("open_id");
        // 企业ID
        int eId = (int) map.get("e_id");
        // 消息ID
        Long msgId = (Long) map.get("msg_id");
        // 创建时间
        Long createTime = ((Integer) map.get("create_time")) + 0L;
        // 媒体ID
        String mediaId = (String) map.get("media_id");


        // 查找坐席和会话服务
        Map agentMaps = findAgentService.findAgentServer(map);
        // 客服ID -1 : 坐席在忙
        String serviceId = (String) agentMaps.get("service_id");
        if ("-1".equals(serviceId)) {
            maps.put("type", 1);
            return maps;
        }
        // 会话ID
        String sessionId = (String) agentMaps.get("session_id");

        // 将消息放到消息缓存列表中
        Message message = new Message();
        String uuid = String.valueOf(msgId);
        message.setUuid(uuid);
        message.setContent(mediaId);
        message.setType(MessageTypeEnums.VOICE.getValue());
        message.setDirection(0);
        message.setCompanyId(String.valueOf(eId));
        message.setSessionId(String.valueOf(sessionId));
        message.setReadStatus(0);
        message.setCreateTime(new Timestamp(createTime));
        redisService.add(sessionId, message);

        // java消息异步接口批处理
        if ("".equals(uuid) || message == null) {
            this.logger.info("saveCustomerMessage：参数为空");
            maps.put("type", 1);
            return maps;
        }
        messageService.saveCustomerMessage(uuid, message);

        // 通知调度有未读信息
        Map messageMap = new HashMap(3);
        messageMap.put("service_id", serviceId);
        messageMap.put("session_id", sessionId);
        messageMap.put("e_id", eId);
        Map sendMessageMaps = webSocketService.sendMessages(messageMap);
        // 0：成功 1：坐席不在线
        int sendMessageResult = (int) sendMessageMaps.get("result");
        if (sendMessageResult == 1) {
            maps.put("type", 1);
            return maps;
        }


        maps.put("type", 0);
        return maps;

    }

    /**
     * 视频消息处理服务
     *
     * @return
     */
    @PostMapping(value = "/videoMessageServer")
    public Map videoMessageServer(@RequestBody Map map) {

        Map<String, Object> maps = new HashMap<String, Object>(2);
        String openId = (String) map.get("open_id");
        // 企业ID
        int eId = (int) map.get("e_id");
        // 消息ID
        Long msgId = (Long) map.get("msg_id");
        // 创建时间
        Long createTime = ((Integer) map.get("create_time")) + 0L;
        // 媒体ID
        String mediaId = (String) map.get("media_id");

        // 查找坐席和会话服务
        Map agentMaps = findAgentService.findAgentServer(map);
        // 客服ID -1 : 坐席在忙
        String serviceId = (String) agentMaps.get("service_id");
        if ("-1".equals(serviceId)) {
            maps.put("type", 1);
            return maps;
        }
        // 会话ID
        String sessionId = (String) agentMaps.get("session_id");

        // 将消息放到消息缓存列表中
        Message message = new Message();
        String uuid = String.valueOf(msgId);
        message.setUuid(uuid);
        message.setContent(mediaId);
        message.setType(MessageTypeEnums.VIDEO.getValue());
        message.setDirection(0);
        message.setCompanyId(String.valueOf(eId));
        message.setSessionId(String.valueOf(sessionId));
        message.setReadStatus(0);
        message.setCreateTime(new Timestamp(createTime));
        redisService.add(sessionId, message);

        // java消息异步接口批处理
        if ("".equals(uuid) || message == null) {
            this.logger.info("saveCustomerMessage：参数为空");
            maps.put("type", 1);
            return maps;
        }
        messageService.saveCustomerMessage(uuid, message);

        // 通知调度有未读信息
        Map messageMap = new HashMap(3);
        messageMap.put("service_id", serviceId);
        messageMap.put("session_id", sessionId);
        messageMap.put("e_id", eId);
        Map sendMessageMaps = webSocketService.sendMessages(messageMap);
        // 0：成功 1：坐席不在线
        int sendMessageResult = (int) sendMessageMaps.get("result");
        if (sendMessageResult == 1) {
            maps.put("type", 1);
            return maps;
        }


        maps.put("type", 0);
        return maps;

    }

    /**
     * 小视频消息处理服务
     *
     * @return
     */
    @PostMapping(value = "/wuliMessageServer")
    public Map wuliMessageServer(@RequestBody Map map) {

        Map<String, Object> maps = new HashMap<String, Object>(2);
        String openId = (String) map.get("open_id");
        // 企业ID
        int eId = (int) map.get("e_id");
        // 消息ID
        Long msgId = (Long) map.get("msg_id");
        // 创建时间
        Long createTime = ((Integer) map.get("create_time")) + 0L;
        // 媒体ID
        String mediaId = (String) map.get("media_id");

        // 查找坐席和会话服务
        Map agentMaps = findAgentService.findAgentServer(map);
        // 客服ID -1 : 坐席在忙
        String serviceId = (String) agentMaps.get("service_id");
        if ("-1".equals(serviceId)) {
            maps.put("type", 1);
            return maps;
        }
        // 会话ID
        String sessionId = (String) agentMaps.get("session_id");

        // 将消息放到消息缓存列表中
        Message message = new Message();
        String uuid = String.valueOf(msgId);
        message.setUuid(uuid);
        message.setContent(mediaId);
        message.setType(MessageTypeEnums.WULI.getValue());
        message.setDirection(0);
        message.setCompanyId(String.valueOf(eId));
        message.setSessionId(String.valueOf(sessionId));
        message.setReadStatus(0);
        message.setCreateTime(new Timestamp(createTime));
        redisService.add(sessionId, message);

        // java消息异步接口批处理
        if ("".equals(uuid) || message == null) {
            this.logger.info("saveCustomerMessage：参数为空");
            maps.put("type", 1);
            return maps;
        }
        messageService.saveCustomerMessage(uuid, message);

        // 通知调度有未读信息
        Map messageMap = new HashMap(3);
        messageMap.put("service_id", serviceId);
        messageMap.put("session_id", sessionId);
        messageMap.put("e_id", eId);
        Map sendMessageMaps = webSocketService.sendMessages(messageMap);
        // 0：成功 1：坐席不在线
        int sendMessageResult = (int) sendMessageMaps.get("result");
        if (sendMessageResult == 1) {
            maps.put("type", 1);
            return maps;
        }


        maps.put("type", 0);
        return maps;

    }

    /**
     * 地理位置消息处理服务
     *
     * @return
     */
    @PostMapping(value = "/positionMessageServer")
    public Map positionMessageServer(@RequestBody Map map) {

        Map<String, Object> maps = new HashMap<String, Object>(2);
        String openId = (String) map.get("open_id");
        // 企业ID
        int eId = (int) map.get("e_id");
        // 消息ID
        Long msgId = (Long) map.get("msg_id");
        // 创建时间
        Long createTime = ((Integer) map.get("create_time")) + 0L;
        // 消息内容
        String content = (String) map.get("content");


        // 查找坐席和会话服务
        Map agentMaps = findAgentService.findAgentServer(map);
        // 客服ID -1 : 坐席在忙
        String serviceId = (String) agentMaps.get("service_id");
        if ("-1".equals(serviceId)) {
            maps.put("type", 1);
            return maps;
        }
        // 会话ID
        String sessionId = (String) agentMaps.get("session_id");

        // 将消息放到消息缓存列表中
        Message message = new Message();
        String uuid = String.valueOf(msgId);
        message.setUuid(uuid);
        message.setContent(content);
        message.setType(MessageTypeEnums.POSITION.getValue());
        message.setDirection(0);
        message.setCompanyId(String.valueOf(eId));
        message.setSessionId(String.valueOf(sessionId));
        message.setReadStatus(0);
        message.setCreateTime(new Timestamp(createTime));
        redisService.add(sessionId, message);

        // java消息异步接口批处理
        if ("".equals(uuid) || message == null) {
            this.logger.info("saveCustomerMessage：参数为空");
            maps.put("type", 1);
            return maps;
        }
        messageService.saveCustomerMessage(uuid, message);

        // 通知调度有未读信息
        Map messageMap = new HashMap(3);
        messageMap.put("service_id", serviceId);
        messageMap.put("session_id", sessionId);
        messageMap.put("e_id", eId);
        Map sendMessageMaps = webSocketService.sendMessages(messageMap);
        // 0：成功 1：坐席不在线
        int sendMessageResult = (int) sendMessageMaps.get("result");
        if (sendMessageResult == 1) {
            maps.put("type", 1);
            return maps;
        }


        maps.put("type", 0);
        return maps;

    }

    /**
     * 链接消息处理服务
     *
     * @return
     */
    @PostMapping(value = "/urlMessageServer")
    public Map urlMessageServer(@RequestBody Map map) {

        Map<String, Object> maps = new HashMap<String, Object>(2);
        String openId = (String) map.get("open_id");
        // 企业ID
        int eId = (int) map.get("e_id");
        // 消息ID
        Long msgId = (Long) map.get("msg_id");
        // 创建时间
        Long createTime = ((Integer) map.get("create_time")) + 0L;
        // 消息内容
        String content = (String) map.get("content");


        // 查找坐席和会话服务
        Map agentMaps = findAgentService.findAgentServer(map);
        // 客服ID -1 : 坐席在忙
        String serviceId = (String) agentMaps.get("service_id");
        if ("-1".equals(serviceId)) {
            maps.put("type", 1);
            return maps;
        }
        // 会话ID
        String sessionId = (String) agentMaps.get("session_id");

        // 将消息放到消息缓存列表中
        Message message = new Message();
        String uuid = String.valueOf(msgId);
        message.setUuid(uuid);
        message.setContent(content);
        message.setType(MessageTypeEnums.URL.getValue());
        message.setDirection(0);
        message.setCompanyId(String.valueOf(eId));
        message.setSessionId(String.valueOf(sessionId));
        message.setReadStatus(0);
        message.setCreateTime(new Timestamp(createTime));
        redisService.add(sessionId, message);

        // java消息异步接口批处理
        if ("".equals(uuid) || message == null) {
            this.logger.info("saveCustomerMessage：参数为空");
            maps.put("type", 1);
            return maps;
        }
        messageService.saveCustomerMessage(uuid, message);

        // 通知调度有未读信息
        Map messageMap = new HashMap(3);
        messageMap.put("service_id", serviceId);
        messageMap.put("session_id", sessionId);
        messageMap.put("e_id", eId);
        Map sendMessageMaps = webSocketService.sendMessages(messageMap);
        // 0：成功 1：坐席不在线
        int sendMessageResult = (int) sendMessageMaps.get("result");
        if (sendMessageResult == 1) {
            maps.put("type", 1);
            return maps;
        }


        maps.put("type", 0);
        return maps;

    }

}
